package com.cmpe451.nutty.mobileapi;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.cmpe451.nutty.controller.SampleJSONControllerV10;
import com.cmpe451.nutty.model.ApiUser;
import com.cmpe451.nutty.model.ApiUserStatus;
import com.cmpe451.nutty.service.TestService;
import com.cmpe451.nutty.utils.JsonResponseException;
import com.cmpe451.nutty.utils.MyLogger;

@Component("authTokenCheckFilter")
public class AuthTokenCheckFilter implements Filter {

	private MyLogger log = MyLogger.getLogger(getClass());

	@Autowired
	private TestService twitterService;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;

		String authToken = req.getHeader("X-nutty-auth");
		String twitterIdStr = req.getHeader("X-nutty-uid");

		if (StringUtils.isBlank(authToken) && StringUtils.isBlank(twitterIdStr)) {
			chain.doFilter(request, response);
			return;
		}

		if (StringUtils.isNotBlank(twitterIdStr)) {
			Long twitterId = Long.parseLong(twitterIdStr);
			// ApiUser apiUser = twitterService.getApiUserByTwitterId(twitterId);
			ApiUser apiUser = null;

			if (apiUser == null) {
				log.info("authTokenCheckFilter.doFilter::User with given twitterId not found::twitterId::{0}", twitterId);
				throw new JsonResponseException(ApiErrorCode.TWITTER_USER_NOT_FOUND, "User with given twitterId not found");
			}

			if (StringUtils.isBlank(authToken)) {
				log.info("authTokenCheckFilter.doFilter::X-tfenos-auth is missing in request header!::twitterId::{0}", twitterId);
				throw new JsonResponseException(ApiErrorCode.AUTH_TOKEN_REQUIRED, "X-tfenos-auth is missing in request header!");
			}

			String genAuthToken = SampleJSONControllerV10.generateAuthToken(apiUser);
			if (!StringUtils.equals(genAuthToken, authToken)) {
				log.info("authTokenCheckFilter.doFilter::Invalid authentication token!::twitterId::{0}", twitterId);
				throw new JsonResponseException(ApiErrorCode.INVALID_AUTHENTICATION_TOKEN, "Invalid authentication token!");
			} else if (apiUser.getStatus() == ApiUserStatus.TWITTER_DISABLED) {
				log.info("authTokenCheckFilter.doFilter::ApiUser removed app from twitter::twitterId::{0}", twitterId);
				throw new JsonResponseException(ApiErrorCode.TWITTER_APP_REMOVED, "Twitter login required!");
			} else {
				ApiThreadLocal.set(apiUser);
			}
		}

		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
	}

}
